import { parseStyle } from './parser'
import * as DEFAULT from './default'

function isNull(obj) {
  return (obj === undefined || obj === null)
}

/**
 * 浅拷贝对象
 */
function shallowCopyObject(obj) {
  const ret = {}
  for(const i in obj) {
    ret[i] = obj[i]
  }
  return ret
}

/**
 * 创建CSS过滤器
 *
 * @param {Object} options
 *   - {Object} whiteList
 *   - {Function} onAttr
 *   - {Function} onIgnoreAttr
 *   - {Function} safeAttrValue
 */
export function CSSFilter(options) {
  options = shallowCopyObject(options || {})
  options.whiteList = options.whiteList || DEFAULT.cssWhiteList
  options.onAttr = options.onAttr || DEFAULT.onAttr
  options.onIgnoreAttr = options.onIgnoreAttr || DEFAULT.onIgnoreAttr
  options.safeAttrValue = options.safeAttrValue || DEFAULT.cssSafeAttrValue
  this.options = options
}

CSSFilter.prototype.process = function(css) {
  // 兼容各种奇葩输入
  css = css || ''
  css = css.toString()
  if(!css) return ''

  const me = this
  const options = me.options
  const whiteList = options.whiteList
  const onAttr = options.onAttr
  const onIgnoreAttr = options.onIgnoreAttr
  const safeAttrValue = options.safeAttrValue

  const retCSS = parseStyle(css, function(sourcePosition, position, name, value, source) {

    const check = whiteList[name]
    let isWhite = false
    if(check === true) isWhite = check
    else if(typeof check === 'function') isWhite = check(value)
    else if(check instanceof RegExp) isWhite = check.test(value)
    if(isWhite !== true) isWhite = false

    // 如果过滤后 value 为空则直接忽略
    value = safeAttrValue(name, value)
    if(!value) return

    const opts = {
      position: position,
      sourcePosition: sourcePosition,
      source: source,
      isWhite: isWhite
    }

    if(isWhite) {
      const ret = onAttr(name, value, opts)
      if(isNull(ret)) {
        return name + ':' + value
      } else {
        return ret
      }
    } else {
      const ret = onIgnoreAttr(name, value, opts)
      if(!isNull(ret)) {
        return ret
      }

    }
  })

  return retCSS
}
